/*
* License:  This  program  is  free  software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the  Free Software Foundation; either version 3 of the License, or (at your
* option)  any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/

package pcgen.CharacterViewer.fragments;

import java.io.File;

import org.apache.commons.lang.StringUtils;

import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import pcgen.android.Logger;

import pcgen.CharacterViewer.R;
import pcgen.CharacterViewer.resources.GameResource;

public class WebTabContentFragment extends AppTabContentFragment
{
	public WebTabContentFragment()
	{
	}
	
	public WebTabContentFragment(String name)
	{
		super(name);
	}
	
	public WebTabContentFragment(GameResource resource)
	{
		super(resource);
	}
	
	public String getContent()
	{
		return _content;
	}
	
	@Override
	public int getLayoutId() 
	{
		return R.layout.tab_content_web;
	}
	
	public String getUrl()
	{
		return _url;
	}

	@Override
	public void onSelected() 
    {
		if (_isStarted && _isDirty)
			load();
    }

    @Override
	public void onUnselected() 
    {
    	if (_viewWeb != null)
    		_viewWeb.clearView();
    }

    @Override
	public void onReselected() 
    {
    }
	
	public void reload()
	{
		_isDirty = true;
		load();
	}
	
	public void updateContent(String content)
	{
		_content = content;
		_url = "";
		_isDirty = true;
	}
	
	public void updateContent(String content, boolean forceReload)
	{
		updateContent(content);
	}
	
	public void updateUrl(String url)
	{
		_content = "";
		_url = url;
		_isDirty = true;
	}
	
	public void updateUrl(String url, boolean forceReload)
	{
		updateUrl(url);
	}
	
	protected WebView getWebView()
	{
		return _viewWeb;
	}
	
	protected void initializeContent(String content, boolean contentIsUrl)
	{
	}
    
    @Override
	protected void initCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
    	super.initCreate(inflater, container, savedInstanceState);
    	
    	setMenuShowRefresh(true);
    	setMenuShowRemove(true);
    }
	
	@Override
	protected void inflateView(View view)
	{
		_viewWeb = (WebView)view.findViewById(R.id.webView1);
		_viewWeb.getSettings().setJavaScriptEnabled(true);
		
		final Fragment reference = this;
		final boolean debugMode = this.getApplication().getDebugMode();
		
		_viewWeb.setWebViewClient(new TabContentFragmentWebViewClient());
		_viewWeb.setWebChromeClient(new WebChromeClient() 
		{
			public boolean onConsoleMessage(ConsoleMessage cm) 
			{
				if (debugMode)
					Toast.makeText(reference.getActivity(), cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId(), Toast.LENGTH_LONG).show();
				return true;  
			}
		});
	}
	
	@Override
	protected void initPause()
	{
		_isStarted = false;
	}
	
	@Override
	protected void initStart()
	{
		try
		{
			load();
		}
		finally
		{
			_isStarted = true;
		}
	}
	
	protected void loadContent()
	{
		if (_viewWeb == null)
			return;
		
		initializeContent(_content, true);
		_viewWeb.loadData(_content, "text/html", "UTF-8");
	}
	
	protected void loadUrl()
	{
		if (_viewWeb == null)
			return;
		
		if (StringUtils.isEmpty(getUrl()))
		{
			_viewWeb.clearView();
			return;
		}
		
		if (!StringUtils.isEmpty(getUrl()))
			initializeContent(getUrl(), true);
		
		File f = new File(_url);
		if (f.exists())
		{
			_viewWeb.loadUrl("file:///" + getUrl());
			return;
		}
		
		_viewWeb.loadUrl(getUrl());
	}
    
    @Override
    protected void refreshResource()
    {
    	try
    	{
			_viewWeb.reload();
    	}
    	catch(Throwable tr)
    	{
    		Logger.e(TAG, "refreshResource", tr);
    	}
    }
    
    @Override
    protected void removeResource()
    {
    	try
    	{
			getActivityEx().removeResource(getResource());
    	}
    	catch(Throwable tr)
    	{
    		Logger.e(TAG, "removeResource", tr);
    	}
    }

	@Override
	protected void stateRestore(Bundle inState)
	{
		try
		{
			_content = inState.getString(KEY_CONTENT);
			_url = inState.getString(KEY_URL);
			
			super.stateRestore(inState);
		}
    	catch(Throwable tr)
    	{
    		Logger.e(TAG, "stateRestore", tr);
    	}
	}
	
	@Override
	protected void stateSave(Bundle outState)
	{
		try
		{
			outState.putString(KEY_CONTENT, _content);
			outState.putString(KEY_URL, _url);
			
			super.stateSave(outState);
		}
    	catch(Throwable tr)
    	{
    		Logger.e(TAG, "stateSave", tr);
    	}
	}
	
	protected void onWebPageFinished(WebView view, String url)
	{	
	}
	
	private void load()
	{
		try
		{
			if (!StringUtils.isEmpty(_url))
				loadUrl();
			
			if (!StringUtils.isEmpty(_content))
				loadContent();
		}
		finally
		{
			_isDirty = false;
		}
	}
	
	private WebView _viewWeb;
	private String _content;
	private String _url;
	
	private boolean _isDirty = false;
	private boolean _isStarted = false;

	private static final String KEY_CONTENT = "KeyContent";
	private static final String KEY_URL = "KeyUrl";

	private static final String TAG = WebTabContentFragment.class.getSimpleName();
	
	private class TabContentFragmentWebViewClient extends WebViewClient 
	{
		@Override
		public void onPageFinished(WebView view, String url)
		{
			onWebPageFinished(view, url);
		}
	}
}
